<?php

namespace App\Admin\Extensions\Tools;

use Encore\Admin\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Tools\AbstractTool;

class ImportButton extends AbstractTool
{

    protected $model;

    public function __construct($model)
    {
        $this->model = $model;
    }
    /**
     * Set up script for import button.
     */
    protected function script()
    {
        return <<<EOT
        $('.import').click(function (e) {
            $('#import').click();
        });
        $('#import').change(function(e){
                var formData = new FormData($('#import-form'));
                formData.append("file",this.files[0]);
                formData.append("model",'{$this->model}');
                $.ajax({
                    url: "/admin/import",
                    type: "POST",
                    data: formData,
                    contentType: false,
                    processData: false,
                    beforeSend:function(){
                        console.log('正在上传')
                    },
                    success:function(data) {
                            toastr.success('操作成功');
                            console.log("上传成功! data=>",data);
                    },
                    complete:function(e,status){
                         if(status='success'){
                            console.log('上传完成');
                            $.pjax.reload('#pjax-container');
                         }
                    },
                    error: function (e) {
                        toastr.error('上传失败',e);
                    }
                });
            })

EOT;


    }

    /**
     * Render import button.
     *
     * @return string
     */
    public function render()
    {
        Admin::script($this->script());
        $url = url('/admin/getExcelTmp',['model'=>$this->model]);
        return <<<EOT


<div class="btn-group pull-right" style="margin-right: 10px">
        <a class="btn btn-sm btn-twitter import"><i class="fa fa-upload"></i> 导入</a>
        <button type="button" class="btn btn-sm btn-twitter dropdown-toggle" data-toggle="dropdown">
            <span class="caret"></span>
            <span class="sr-only">Toggle Dropdown</span>
        </button>
        <ul class="dropdown-menu" role="menu">
            <li><a href="{$url}" target="_blank">下载模板</a></li>
        </ul>
        <input type="file" style="display:none" id="import" accept=".cvs,.xls,.xlsx">
</div>

&nbsp;&nbsp;

EOT;
    }
}
